package com.vcredit.creditcat.service.speedloan.lrh;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.vcredit.creditcat.dto.speedloan.CheckCustResultDto;
import com.vcredit.creditcat.model.AuthIdentity;
import com.vcredit.creditcat.model.AuthProccess;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.model.ProductCheckcustItem;
import com.vcredit.creditcat.service.AuthIdentityService;
import com.vcredit.creditcat.service.AuthProccessService;
import com.vcredit.creditcat.service.speedloan.CommonProductCheckCustService;
import com.vcredit.creditcat.service.speedloan.ProductCheckCustServiceAdaptor;
import com.vcredit.creditcat.vo.product.lrh.CheckSubmit;
import com.vcredit.creditcat.vo.product.lrh.LrhGetCheck;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.exception.BaseException;
import com.vcredit.framework.util.HttpRequest;
import com.vcredit.framework.util.JacksonUtil;

@Service(ProductCheckCustServiceAdaptor.BEANNAME_PREFIX + 36)
public class LrhCheckCustService extends CommonProductCheckCustService {

	private static final Logger logger = LoggerFactory.getLogger(LrhCheckCustService.class);

	@Value("${xinyongmao.publicKey}")
	private String publicKey;

	@Value("${product.lrh.url}")
	private String url;

	@Value("${product.lrh.appkey}")
	private String appKey;

	@Value("${product.lrh.appSecret}")
	private String appSecret;

	@Autowired
	AuthIdentityService authIdentityService;

	@Autowired
	AuthProccessService authProccessService;

	private String source = "XINYONGMAO";
	private String lrhCheck = "/isCanDecision";
	private String lrhPost = "/applyDecision";
	private String lrhSearch = "/queryDecision";
	private String version = "1.0";

	@Override
	public CheckCustResultDto handlerCheckItem(ProductCheckcustItem checkItem, int itemType, Cust cust,
			Long productId) {
		int itemId = Integer.parseInt(checkItem.getCheckItemId() + "");
		if (itemType == 0) { // 原始认证项
			switch (itemId) {
			case 1:
				// 执行高级实名完成后的校验规则
				try {
					// 校验男性不能申请此产品
					if (!checkSex(cust)) {
						return CheckCustResultDto.fail("您是一枚纯爷们儿，目前的贷款不太适合您~");
					}

					// 校验撞库
					if (!checkCredit(cust)) {
						return CheckCustResultDto.fail("根据系统判断，您目前不符合申请条件");
					}

					return CheckCustResultDto.success();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case 2:
				// 执行手机认证完成后的校验规则
				break;

			default:
				break;
			}
		} else { // 补充认证项
			switch (itemId) {
			case 1:
				// 执行基本信息完成后的校验规则
				break;
			case 2:
				// 执行手机认证完成后的校验规则
				break;

			default:
				break;
			}
		}

		return CheckCustResultDto.success();
	}

	private boolean checkCredit(Cust cust) throws Exception {

		AuthIdentity authIdentity = authIdentityService.findByProcessId(cust.getLastProccessId());

		// 生成签名
		String sign = "";// 签名串
		String customerName = authIdentity.getName();
		String idcardNo = authIdentity.getCitizenId();
		String faceRecognitionScore = authIdentity.getLiveCompareValue().toString();
		TreeMap<String, String> parameterMap = new TreeMap<String, String>();
		parameterMap.put("caller", source);
		parameterMap.put("version", "1.0");
		parameterMap.put("appKey", appKey);
		parameterMap.put("customerName", customerName);
		parameterMap.put("idcardNo", idcardNo);
		parameterMap.put("faceRecognitionScore", faceRecognitionScore);

		sign = createSign(appSecret, parameterMap);

		// 组装提交参数
		CheckSubmit checkSubmit = new CheckSubmit();
		checkSubmit.setCaller(source);
		checkSubmit.setVersion(version);
		checkSubmit.setAppKey(appKey);
		checkSubmit.setSign(sign);
		checkSubmit.setCustomerName(customerName);
		checkSubmit.setIdcardNo(idcardNo);
		checkSubmit.setFaceRecognitionScore(faceRecognitionScore);

		// lrh返回
		String submitJason = JacksonUtil.Obj2Json(checkSubmit);
		logger.info("lrh:" + lrhCheck + "#" + submitJason);
		String resultJson = HttpRequest.doJson(url + lrhCheck, submitJason, 30);
		LrhGetCheck result = JacksonUtil.Json2Obj(resultJson, new TypeReference<LrhGetCheck>() {
		});
		logger.info("lrh:" + lrhCheck + "#" + JacksonUtil.Obj2Json(result));

		if (result.getStatus() == 1) {
			return true;
		} else if (result.getStatus() == -1) {			
			throw new BaseException(result.getMessage());
		}else if (result.getStatus() ==0||result.getStatus() ==2) {			
			return false;
		} else {
			return true;
		}
	}

	private boolean checkSex(Cust cust) throws Exception {

		AuthIdentity authIdentity = authIdentityService.findByProcessId(cust.getLastProccessId());

		String identityNo = authIdentity.getCitizenId();

		String sex = "";
		if (identityNo.length() == 15) {
			String mes = identityNo.substring(identityNo.length() - 1, identityNo.length());
			if (("1,3,5,7,9").indexOf(mes) > -1) {
				sex = "男";
			} else {
				sex = "女";
			}
		} else if (identityNo.length() == 18) {
			String mes = identityNo.substring(identityNo.length() - 2, identityNo.length() - 1);
			if (("1,3,5,7,9").indexOf(mes) > -1) {
				sex = "男";
			} else {
				sex = "女";
			}
		}
		if (sex.equals("男")) {
			return false;
		}
		return true;
	}

	@Log
	private String createSign(String appSecret, TreeMap parameterMap) throws Exception {

		String sign = appSecret;
		Iterator<Map.Entry<String, String>> it = parameterMap.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			if (!((String) entry.getKey()).equals("sign")) {
				sign = sign + (String) entry.getKey() + (String) entry.getValue();
			}
		}
		sign = sign + appSecret;
		try {
			// MD5加密
			sign = md5Encode2UpperCase(sign);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("丽人荟:Md5加密出现异常:");
			throw e;
		}
		return sign;
	}

	/**
	 * md5加密
	 * 
	 * @param sign
	 * @return
	 * @throws Exception
	 */
	@Log
	private static String md5Encode2UpperCase(String sign) throws Exception {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			logger.info(e.getMessage());
			return "";
		}
		byte[] byteArray = sign.getBytes("UTF-8");
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = md5Bytes[i] & 0xFF;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		String rs = hexValue.toString().toUpperCase();
		return rs;
	}

}
